package com.lepu.app.fun.mother_circle.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.app.utils.AppEnterTongJi;
import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragment;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.Observer;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.UmengHelper;
import com.eyzhs.app.R;
import com.lepu.app.fun.mother_circle.MotherCircleAllActivity;
import com.lepu.app.fun.mother_circle.adapter.AdapterMotherCircle;
import com.lepu.app.fun.mother_circle.bean.BeanMotherCircle;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.widget.ListViewForScrollview;

public class FragmentMotherCircle extends BaseFragment implements AsyncRequest , Observer{

	private static final String REQUEST_DATA = "request_data";

	private static final int MSG_DATA_SUCCESS = 10;
	private static final int MSG_DATA_FAIL = 11;

	// ========================================================================
	private static FragmentMotherCircle mInstance = null;

	private ScrollView mCircleScrollView = null;
	private ListViewForScrollview mCircleAddListView = null;
	private ListViewForScrollview mCircleNotAddListView = null; 
	private LinearLayout mCircleNotAddLayout = null;
	
	public boolean mInitDataSuccess = false;

	public ArrayList<BeanMotherCircle> mDataList;
	
	private View mMainView = null;
	private LinearLayout mInterestLayout;

	public static FragmentMotherCircle getInstance() {
		return mInstance;
	}

	@SuppressLint("InflateParams")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mInstance = this;
		mMainView = LayoutInflater.from(getActivity()).inflate(R.layout.mother_circle_fragment, null, false);
		init();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);

		ViewGroup p = (ViewGroup) mMainView.getParent();
		if (p != null) {
			p.removeAllViewsInLayout();
		}
		return mMainView;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		mInitDataSuccess = false;
		mInstance = null;
	}

	@Override
	public void onResume() {
		super.onResume();
		UmengHelper.OnPageStart("4");
	}

	@Override
	public void onPause() {
		super.onPause();
		UmengHelper.OnPageEnd("4");
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);

		if (isVisibleToUser) {
			if (!mInitDataSuccess) {
				request();	
				showFirstLoadDataLayout(true);
			}
		}
	}
	
	private void showHideNoDataLayout(boolean isShow)
	{
		LinearLayout noDataLayout = (LinearLayout) mMainView.findViewById(R.id.noDataLayout);
		if(noDataLayout != null)
		{
			if(isShow)
			{if(mDataList == null || mDataList.size() == 0)
					{
						noDataLayout.setVisibility(View.VISIBLE);
						mCircleScrollView.setVisibility(View.GONE);
					}
				
			}else{
				noDataLayout.setVisibility(View.GONE);
				mCircleScrollView.setVisibility(View.VISIBLE);
			}
		}
	}
	
	private void showFirstLoadDataLayout(boolean isShow)
	{
		LinearLayout firstLoadDataLayout = (LinearLayout) mMainView.findViewById(R.id.firstLoadDataLayout);
		if(firstLoadDataLayout != null)
		{
			if(isShow)
			{
				if(mDataList == null || mDataList.size() == 0)
				{
					firstLoadDataLayout.setVisibility(View.VISIBLE);
				}
				
				LinearLayout noDataLayout = (LinearLayout) mMainView.findViewById(R.id.noDataLayout);
				noDataLayout.setVisibility(View.GONE);
			}else{
				firstLoadDataLayout.setVisibility(View.GONE);
			}
		}
	}

	@SuppressLint("ResourceAsColor")
	private void init() {
		mCircleScrollView = (ScrollView) mMainView.findViewById(R.id.circleScrollView);
		mCircleAddListView =  (ListViewForScrollview) mMainView.findViewById(R.id.circleAddListView);
		mCircleNotAddListView =  (ListViewForScrollview) mMainView.findViewById(R.id.circleNotAddListView);
		mCircleNotAddLayout = (LinearLayout) mMainView.findViewById(R.id.circleNotAddLayout);
		mInterestLayout = (LinearLayout)mMainView.findViewById(R.id.circleInterestLayout);
		
		ObserverManager.getInstance().addObserver(ObserverConst.NOTIFY_MOTHER_CIRCLE_CHANGE, this);
		
		LinearLayout circleAddButton = (LinearLayout) mMainView.findViewById(R.id.circleAddButton);
		circleAddButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				
				AppEnterTongJi.clickEvent(52, "");
				
				Intent intent = new Intent(getActivity(), MotherCircleAllActivity.class);
				MainTabActivity.getInstance().startActivity(intent,true);
				
			}
		});
	}

	//请求数据
	@SuppressLint("DefaultLocale")
	public void request() {
		String url = Setting.getCircleListUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
		
		} catch (Exception e) {
		}
		map.put("ht", params);
		
		String temp = String.format("?key=%d", System.currentTimeMillis());
		ApiClient.http_post(url+temp, map, null, this, REQUEST_DATA, true,false,true);
	}

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_DATA_SUCCESS:
				showFirstLoadDataLayout(false);
				
				ArrayList<BeanMotherCircle> dataList = (ArrayList<BeanMotherCircle>) msg.obj;
				if (dataList != null && dataList.size() > 0) {
					mInitDataSuccess = true;
					showHideNoDataLayout(false);
					mDataList = dataList;
					
					ArrayList<BeanMotherCircle> dataArrayList1 = new ArrayList<BeanMotherCircle>();
					ArrayList<BeanMotherCircle> dataArrayList2 = new ArrayList<BeanMotherCircle>();
					for(int i=0; i<dataList.size(); i++){
						if(dataList.get(i).cricleType == 1){
							dataArrayList1.add(dataList.get(i));
						}else{
							if(dataList.get(i).cricleTypeInterest == 1){
								dataArrayList2.add(dataList.get(i));
							}
						}
					}
					
					if(dataArrayList1.size() == 0){
						mCircleNotAddLayout.setVisibility(View.VISIBLE);
						mCircleAddListView.setVisibility(View.GONE);
					}else{
						mCircleNotAddLayout.setVisibility(View.GONE);
						mCircleAddListView.setVisibility(View.VISIBLE);
						AdapterMotherCircle dataAdapter1 = new AdapterMotherCircle(getActivity(),dataArrayList1,"FragmentMotherCircle");
						mCircleAddListView.setAdapter(dataAdapter1);
					}
					
					if(dataArrayList2.size() == 0){
						mInterestLayout.setVisibility(View.GONE);
					}else{
						mInterestLayout.setVisibility(View.VISIBLE);
					}
					AdapterMotherCircle dataAdapter2 = new AdapterMotherCircle(getActivity(),dataArrayList2,"FragmentMotherCircle");
					mCircleNotAddListView.setAdapter(dataAdapter2);
					
				} else {
                    showHideNoDataLayout(true);
				}

				break;
			case MSG_DATA_FAIL:
				showFirstLoadDataLayout(false);
				showHideNoDataLayout(true);
				break;

			default:
				break;
			}
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			ArrayList<BeanMotherCircle> dataArraylist = BeanMotherCircle.parseJsonData((String) data);

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = dataArraylist;
			mHandler.sendMessage(msg);
		}  
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_DATA)) {
			mHandler.sendEmptyMessage(MSG_DATA_FAIL);
		} 
	}

	@Override
	public void notify(String arg0, Object arg1, Object arg2) {
		request();
	}

}
